package homework;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class ServerLiu {
    private ServerSocket serverSocket;
    public ServerLiu()
    {
        try {
            System.out.println("服务器启动.....");
            serverSocket = new ServerSocket(8488);
            System.out.println("服务端连接成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void start() {
        try {
            int number = 0;
            System.out.println("等待客户端连接.....");
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("第"+(++number)+"个客户端连接成功!");
                Thread t1 = new Thread(new ClientHandler(socket, number));
                t1.start();
            }
//            InputStream in = socket.getInputStream();
//            int len;
//            while ((len = in.read())!=-1) {
//                byte[] bytes = new byte[len];
//                in.read(bytes);
//                String message = new String(bytes, StandardCharsets.UTF_8);
//                System.out.println("客户端说："+message);
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public class ClientHandler implements Runnable {
        private  Socket socket;
        int number;

        public ClientHandler(Socket socket, int number) {
            this.socket = socket;
            this.number = number;
        }

        public ClientHandler() {
        }

        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                int len;
                while ((len = in.read())!=-1) {
                    byte[] bytes = new byte[len];
                    in.read(bytes);
                    String message = new String(bytes, StandardCharsets.UTF_8);
                    System.out.println("第"+number+"客户端说："+message);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        ServerLiu server = new ServerLiu();
        server.start();
    }

}
